// App.jsx
import React, { useState, useEffect } from "react";

export default function App() {
  const [tasks, setTasks] = useState(() => {
    const saved = localStorage.getItem("my_tasks");
    return saved ? JSON.parse(saved) : [];
  });
  const [input, setInput] = useState("");

  useEffect(() => {
    localStorage.setItem("my_tasks", JSON.stringify(tasks));
  }, [tasks]);

  const addTask = () => {
    if (input.trim() === "") return;
    setTasks([...tasks, { id: Date.now(), title: input, completed: false }]);
    setInput("");
  };

  const toggleTask = (id) => {
    setTasks(
      tasks.map((t) =>
        t.id === id ? { ...t, completed: !t.completed } : t
      )
    );
  };

  const deleteTask = (id) => {
    setTasks(tasks.filter((t) => t.id !== id));
  };

  return (
    <div className="min-h-screen bg-gradient-to-r from-blue-100 to-purple-100 p-6">
      <div className="max-w-xl mx-auto bg-white shadow-xl rounded-2xl p-6">
        <h1 className="text-3xl font-bold text-center text-purple-600 mb-4">
          任务管理系统
        </h1>

        <div className="flex mb-6 gap-2">
          <input
            type="text"
            className="flex-grow p-2 border rounded-lg"
            placeholder="请输入任务内容..."
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && addTask()}
          />
          <button
            className="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 transition"
            onClick={addTask}
          >
            添加任务
          </button>
        </div>

        <ul className="space-y-2">
          {tasks.length === 0 ? (
            <li className="text-gray-500 text-center">暂无任务</li>
          ) : (
            tasks.map((task) => (
              <li
                key={task.id}
                className={`flex justify-between items-center bg-gray-50 border rounded-lg p-3 shadow-sm ${
                  task.completed ? "opacity-60 line-through" : ""
                }`}
              >
                <span
                  className="cursor-pointer"
                  onClick={() => toggleTask(task.id)}
                >
                  {task.title}
                </span>
                <button
                  className="text-sm text-red-500 hover:text-red-700"
                  onClick={() => deleteTask(task.id)}
                >
                  删除
                </button>
              </li>
            ))
          )}
        </ul>

        <div className="mt-6 text-sm text-gray-500 text-center">
          已创建任务 {tasks.length} 个，完成 {tasks.filter((t) => t.completed).length} 个
        </div>
      </div>
    </div>
  );
}
